package com.example.activity.service;

import com.alibaba.fastjson.JSON;
import com.example.activity.TemplateDao;
import com.example.activity.dto.ActivityTemplateContext;
import com.example.activity.dto.ext.EvenTemplateExt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * @author Houger.
 * @date 2024年12月13日 16:07.
 */
@Slf4j
@Service
public class TemplateService {

    public void addAndUpdate(ActivityTemplateContext<EvenTemplateExt> context) {

        this.insert(context);
        log.info("执行 TemplateService addAndUpdate: {}", context);
    }

    private void insert(ActivityTemplateContext<EvenTemplateExt> context) {
        TemplateDao dao = this.mapper(context);
        log.info("insert to db: {}", dao);
    }

    private TemplateDao mapper(ActivityTemplateContext<EvenTemplateExt> context) {
        TemplateDao dao = new TemplateDao();
        BeanUtils.copyProperties(context, dao);
        dao.setExt(JSON.toJSONString(context.getExt()));
        return dao;
    }

    private ActivityTemplateContext<EvenTemplateExt> mapper(TemplateDao dao) {
        ActivityTemplateContext<EvenTemplateExt> context = new ActivityTemplateContext<>();
        BeanUtils.copyProperties(dao, context,"ext");
        context.setExt(JSON.parseObject(dao.getExt(), EvenTemplateExt.class));
        return context;
    }

    public ActivityTemplateContext<EvenTemplateExt> search(ActivityTemplateContext<EvenTemplateExt> context) {
        log.info("执行 TemplateService search");
        TemplateDao dao=this.getForDb(context);
        context = this.mapper(dao);
        return context;
    }

    private TemplateDao getForDb(ActivityTemplateContext<EvenTemplateExt> context) {
        TemplateDao dao = new TemplateDao();
        dao.setId(1);
        dao.setTemplateId("1");
        dao.setTemplateName("event活动模版");
        dao.setExt("{\"limit\":1,\"limitUser\":1}");
        return dao;
    }

    public void delete(ActivityTemplateContext<EvenTemplateExt> context) {
        log.info("执行 TemplateService delete:  {}", JSON.toJSONString(context));
    }
}
